package com.eelye.util.spring;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * Spring ApplicationContext 工具类
 */
@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static <T> T getBean(String beanName) {
        if(applicationContext.containsBean(beanName)){
            return (T) applicationContext.getBean(beanName);
        }else{
            return null;
        }
    }

    public static <T> Map<String, T> getBeansByType(Class<T> baseType){
        return applicationContext.getBeansOfType(baseType);
    }

    public static String GetProperty(String path) {
        Environment env = getBean("environment");
        return env.getProperty(path);
    }

    /**
     * 获取当前环境
     */
    public static String getActiveProfile() {
        return applicationContext.getEnvironment().getActiveProfiles()[0];
    }

    public static void clearSchedulingTask() {
        Map<String, TaskScheduler> beanMap = getBeansByType(TaskScheduler.class);
        for (Map.Entry<String, TaskScheduler> schedulerEntry : beanMap.entrySet()) {
            TaskScheduler bean = schedulerEntry.getValue();
            if (bean instanceof ThreadPoolTaskScheduler) {
                ScheduledExecutorService executor = ((ThreadPoolTaskScheduler) bean).getScheduledExecutor();
                ((ScheduledThreadPoolExecutor)executor).getQueue().clear();

                break;
            }
        }
    }
}
